<template>
  <div style="font-family: 微软雅黑;position: relative" class="homeWrapper">
    <big-gift v-if="showBigGift == 2" :gifts="gifts"></big-gift>
    <div class="indexTop">
      <choose-area @change-city="changeCity" :values="values" :dates="citys"></choose-area>
    </div>
    <div v-show="showContent" class="indexMiddle">
      <scroller :pulldown-config="pulldownConfig" :pullup-config="pullupConfig" height="100%" lock-x scrollbar-y use-pullup use-pulldown
                @pullup:loading="loadMore" @pulldown:loading="refresh" :pullup-status.sync="pullupStatus" v-ref:scroller>
        <div class="main-container">
          <div style="width: 100%;">
            <carousel :imgs="carouselImg" v-if="carouselStatus" ref="carousel"></carousel>
            <div class="line"></div>
            <slideadv :list="notices"></slideadv>
            <div class="line"></div>
            <div class="product-menu">
              <table-menu>
                <slide-item slot="table-item" v-for="(index,item) in menuData" :menu-obj="item"
                            @click="clickProductMenu(item.classId,item.closetime,item.classImage)"></slide-item>
              </table-menu>
            </div>
            <div class="line"></div>
            <signmenu :activtys="detailActivitys"></signmenu>
            <div class="h2"></div>
            <tab style="font-size: 2.5rem" active-color="#FFA500" bar-active-color="bar-active-color" animate>
              <tab-item selected @click="clickSwitchItem(0)">本周热卖</tab-item>
              <tab-item @click="clickSwitchItem(1)">人气新品</tab-item>
            </tab>

          </div>
          <div class="product-box">
            <div v-if="productState == 'hot'" class="product-list">
              <product-item @show-popup="showPopup" @del="delCart" @add="addCart" :product-no="index" :product="item"
                            v-for="(index,item) in productHot">
              </product-item>
            </div>
            <div v-if="productState == 'new'" class="product-list">
              <product-item @show-popup="showPopup" @del="delCart" @add="addCart" :product-no="index" :product="item"
                            v-for="(index,item) in productNew"></product-item>
            </div>
            <!--<div class="home-tab-box"></div>-->
          </div>

        </div>
      </scroller>
    </div>
    <div class="indexBottom"></div>
    <div @click="toCart" class="home-cart">
      <cart :num="cartNum" :total-price="cartTotalPrice"></cart>
    </div>
    <div @click="hidePop" v-show="showPop" class="pop-container">
      <div class="pop-bg"></div>
      <img class="bigImg" :src="bigImage" alt="">
    </div>
  </div>

</template>
<script>
  import carousel from './../components/carousel.vue'
  import slideadv from './../components/menu/slide-adv.vue'
  import signmenu from './../components/menu/sign-menu.vue'
  import ProductItem from './../components/product/product-item.vue'
  import Scroller from './../../components/scroller/index.vue'
  import Spinner from './../../components/spinner/index.vue'
  import SlideItem from './../components/menu/slide-item.vue'
  import Tab from './../../components/tab/tab.vue'
  import TabItem from './../../components/tab/tab-item.vue'
  import TableMenu from './../components/menu/table-menu.vue'
  import Cart from './../components/menu/suspension-cart.vue'
  import ChooseArea from './../components/menu/choose-area.vue'
  import {go} from './../../libs/router'
  import bigGift from './../components/bigGift/bigGift.vue'

  import {couponClick, selectedCoupon, addressClick,openid, detailActivitys, showBigGift, bigGifts,QRCodeId} from './../../vuex/getters.js'
  import {set_couponClick, set_selectedCoupon, update_address_click,set_openid, set_detailActivitys, set_showBigGift, set_bigGift,set_QRCodeId} from './../../vuex/actions.js'
  var MyRequest = require('./../../commons/js/MyRequest.js');
  var Global = require('./../../commons/js/Global.js')
  var CartUtils = require('./../../commons/js/Cart');
  var utils = require('./../../commons/js/utils');
  var LocalStorageUtils = require('./../../commons/js/LocalStorageUtil');
  export default {
    data () {
      return {
        gifts: [],
        carouselStatus: true,
        carouselImg: [],
        menuData: [],
        notices: [],
        detailActivitys: [],
        productState: "hot",
        c_index: 0,
        choose: 'choosed',
        no_choose: 'no-choosed',
        productHot: [],
        productNew: [],
        pullupEnabled: true,
        pullupStatus: 'default',
        pageNo: 0,
        pageSize: 10,
        pulldownConfig: {
          content: '下拉刷新',
          downContent: '松开进行加载',
          upContent: '下拉刷新',
          loadingContent: '加载中...',
          height:30
        },
        pullupConfig: {
          content: '上拉加载更多',
          downContent: '松开进行加载',
          upContent: '上拉加载更多',
          loadingContent: '加载中...'
        },
        cartNum: 0,
        cartTotalPrice: 0,
        cityId: "",
        cityName: "",
        citys: [],
        values: [],
        showPop: false,
        bigImage: "",
        showContent:false
      }
    },
    components: {
      carousel,
      slideadv,
      signmenu,
      ProductItem,
      Scroller,
      Spinner,
      SlideItem,
      Tab,
      TabItem,
      TableMenu,
      Cart,
      ChooseArea,
      bigGift
    },
    created: function () {
    },
    vuex: {
      getters: {
        couponClick,
        selectedCoupon,
        addressClick,
        openid,
        detailActivitys,
        showBigGift,
        bigGifts,
        QRCodeId
      },
      actions: {
        set_couponClick,
        set_selectedCoupon,
        update_address_click,
        set_openid,
        set_detailActivitys,
        set_showBigGift,
        set_bigGift,
        set_QRCodeId
      }
    },
    methods: {
      getBigGift () {
        var data = {
          mobile : LocalStorageUtils.getItem("User").mobile
        }
        MyRequest.MyGet("BigGift", this, function (result, that) {
          console.log(result)
          if(result.success) {
            var mobile = LocalStorageUtils.getItem("User").mobile
            mobile = mobile.substring(mobile.length - 4, mobile.length)
            var curGifts = []
            for(var i = 0; i < result.data.length; i ++) {
              var item = result.data[i]
              //console.log(item.bettwenTime)
              //item.activeTime = (item.bettwenTime.split("~"))[1]
              item.activeTime = Global.getNewDay(Global.getCurDay(), item.deadTime)
              item.lastMobile = mobile
              curGifts.push(item)
              that.set_showBigGift(2)
            }
            console.log(curGifts)
            that.gifts = curGifts
          } else {
            that.set_showBigGift(false)
          }
        }, data)
      },
      clickSwitchItem(index){
        if (index == 0) {
          this.productState = "hot";
        } else {
          this.productState = "new";
        }
        this.$refs.scroller.reset()
        this.c_index = index;
      },
      clickProductMenu(classId, closeTime, bigImg){
        this.$router.go({name: 'ProductList', query: {classId: classId, closetime: closeTime, classImage: bigImg}});
      },
      loadMore (uuid) {
        //加载更多
        if (this.productState == 'hot') {
          this.pageNo++;
          var b = this.pageNo * this.pageSize + 1;
          var data = {
            action: "findAllHotProduct",
            cityId: this.cityId,
            begin: b,
            end: this.pageSize
          };
          MyRequest.MyGet("HotProduct", this, function (result, that) {
            var currentDate = utils.getCurrentDate();
            var carts = CartUtils.getCartStorage();
            var s = "http://static.52letsgo.cn/";
            for (var i = 0; i < result.data.length; i++) {
              result.data[i].type = "product-cell-3";
              result.data[i].productNo = (b + i);
              result.data[i].bigImage = s + result.data[i].bigImage;
              result.data[i].horImage = s + result.data[i].horImage;
              result.data[i].image = s + result.data[i].image;
              var num = 0;
              for (var j = 0; j < carts.length; j++) {
                if (carts[j].productId == result.data[i].id && carts[j].date == currentDate) {
                  num = carts[j].num;
                  break;
                }
              }
              result.data[i].cartNum = num;
              that.productHot.push(result.data[i]);
              //that.productHot[that.productHot.length] = result.data[i];
            }
            if (result.data.length < that.pageSize){
              that.$broadcast('pullup:disable',uuid)
            }
            that.$nextTick(() => {
              that.$broadcast('pullup:reset', uuid);
              that.$refs.scroller.reset()
            })
          }, data);
        } else {
          this.$nextTick(() => {
            this.$broadcast('pullup:reset', uuid);
            this.$refs.scroller.reset()
          })
        }
      },
      refresh (uuid) {
        this.pageNo = 0;
        this.$broadcast('pullup:enable', uuid)
        this.init(uuid);
//          setTimeout(() => {
//            this.n = 10
//
//          }, 2000)
      },
      setTopBanner(data){
        var bannerData = new Array();
        if (!data || !data.length){
          this.carouselImg = bannerData;
          return;
        }
        for (var i = 0; i < data.length; i++) {
          var obj = {
            url: data[i].linkUrl,  //这里填写图片点击的链接
            img: data[i].picture
          }
          bannerData[bannerData.length] = obj;
        }
        this.carouselImg = bannerData;
      },
      setNotice(data,noticeTime){
        var n = new Array();
        for (var i = 0; i < data.length; i++) {
          var d = data[i].mobile
            + "点了"
            + data[i].productName
            + "  "
            + data[i].productCount + "份";
          n[n.length] = d;
        }
        if (n.length <= 0){
            for (var i=0;i<noticeTime.length;i++){
              var d = noticeTime[i].title;
              n[n.length] = d;
            }
        }
        this.notices = n;
      },
      setDetailActivty(data){
        this.detailActivitys = data
        LocalStorageUtils.setItem("detailActivitys", data)
      },
      setProductMenu(data){
        this.menuData = data;
      },
      setProductHot(data){
        var s = "http://static.52letsgo.cn/";
        var currentDate = this.currentDate;
        var carts = CartUtils.getCartStorage();
        for (var i = 0; i < data.length; i++) {
          if (i == 0) {
            data[i].type = "product-cell-1";
          } else if (i == 1) {
            data[i].type = "product-cell-2";
          } else {
            data[i].type = "product-cell-3";
          }
          data[i].productNo = (i + 1);
          data[i].bigImage = s + data[i].bigImage;
          data[i].horImage = s + data[i].horImage;
          data[i].image = s + data[i].image;
          var num = 0;
          for (var j = 0; j < carts.length; j++) {
            if (carts[j].productId == data[i].id && carts[j].date == currentDate) {
              num = carts[j].num;
              break;
            }
          }
          data[i].cartNum = num;
        }
        this.productHot = data;
        this.$refs.scroller.reset();
      },
      setProductNew(data){
        var s = "http://static.52letsgo.cn/";
        var currentDate = this.currentDate;
        var carts = CartUtils.getCartStorage();
        for (var i = 0; i < data.length; i++) {
          data[i].type = "product-cell-3";
          data[i].productNo = 0;
          data[i].bigImage = s + data[i].bigImage;
          data[i].horImage = s + data[i].horImage;
          data[i].image = s + data[i].image;
          var num = 0;
          for (var j = 0; j < carts.length; j++) {
            if (carts[j].productId == data[i].id && carts[j].date == currentDate) {
              num = carts[j].num;
              break;
            }
          }
          data[i].cartNum = num;
        }
        this.productNew = data;
        this.$refs.scroller.reset();
      },
      init(uuid){
        var data = {
          action: "home_info",
          cityId: this.cityId
        };
        MyRequest.MyGetWithToast("Home", this, function (result, that) {
          console.log(that.showBigGift)
          that.setTopBanner(result.data.centerAd);
          that.setNotice(result.data.notice,result.data.noticeTime);
          that.setDetailActivty(result.data.dailyActivity);
          that.setProductMenu(result.data.productClasses);
          that.setProductHot(result.data.hotProduct);
          that.setProductNew(result.data.newProduct);
          that.showContent = true;
          Global.closeLoading();
          if (uuid != -1) {
            that.$nextTick(() => {
              that.$broadcast('pulldown:reset', uuid)
            })
          }
          if(that.showBigGift == 1) {
            console.log(that.bigGifts)
            that.gifts = that.bigGifts
            that.set_showBigGift(2)
          }
        }, data);
      },
      addCart(index){
        if (this.productState == "hot") {
          var num = this.productHot[index].cartNum;
          num++;
          this.productHot[index].cartNum = num;
        } else if (this.productState == "new") {
          var num = this.productNew[index].cartNum;
          num++;
          this.productNew[index].cartNum = num;
        }
        var date = this.currentDate;
        var day = this.currentDay;
        CartUtils.addCartStorage(this.productHot[index], date, day);
        this.initCart();
      },
      delCart(index){
         var date = this.currentDate;
        var id = this.productHot[index].id;
        if (this.productState == "hot") {
          var num = this.productHot[index].cartNum;
          num--;
          this.productHot[index].cartNum = num;
        } else if (this.productState == "new") {
          var num = this.productNew[index].cartNum;
          num--;
          this.productNew[index].cartNum = num;
          id = this.productNew[index].id;
        }
        CartUtils.delCart(id, date);
        this.initCart();
      },
      toCart() {
          if (this.judgeLogin()){
            this.set_couponClick(false);
            this.set_selectedCoupon('');
            this.update_address_click(false);
            this.$router.go({name: 'cart'});
          }
      },
      initCart(){
        this.cartNum = CartUtils.countCartNum();
        this.cartTotalPrice = CartUtils.getTotalPrice();
      },
      getCity(){
        var data = {
          action: "list"
        }
        MyRequest.MyGet("Citys", this, function (result, that) {
          if (result.success) {
            var data = result.data;
            var d = new Array();
            for (var i = 0; i < data.length; i++) {
              var obj = {
                name: data[i].cityName,
                value: "id" + data[i].id
              }
              d.push(obj);
            }
            var v = new Array();
//            {
//              name:that.cityName,
//                value:"id"+that.cityId
//            }
            //v.push(that.cityName);
            var citys = new Array();
            citys.push(d);
            that.values = v;
            that.citys = citys;
          }

        }, data);
      },
      changeCity(id){
        if (id != this.cityId) {
          this.cityId = id;
          var citys = this.citys[0];
          for (var i = 0; i < citys.length; i++) {
            var curId = "id"+id;
            if (curId == citys[i].value) {
              LocalStorageUtils.setCity(id, citys[i].name);
              break;
            }
          }
          this.init(-1);
        }
      },
      getActiveDay(){
        var data = {
          action: "weekday"
        };
        MyRequest.MyGet("ActiveDay", this, function (result, that) {
          var data = result.data;
          for (var i = 0; i < data.length; i++) {
//            data[i].weekday = utils.solveDate(data[i].wday);
            if (data[i].state == 2) {
              that.currentDate = data[i].wdate;
              that.currentDay = data[i].wday;
            }
          }
        }, data);
      },
      showPopup(index, url){
        this.showPop = true;
        this.bigImage = url;
      },
      hidePop(){
        this.showPop = false;
      },
      scrollListener(position){
      },
      judgeLogin () {
        if (!LocalStorageUtils.getItem("User") || !LocalStorageUtils.getItem("User").id) {
          this.$router.go({path: '/login'})
          return false
        }
        return true
      },
    },
    beforeDestroy () {

    },
    ready: function () {
      Global.closeLoading();
      var user = LocalStorageUtils.getItem("User");
      var city = LocalStorageUtils.getItem("city");
      if (city) {
        this.cityId = city.id;
        this.cityName = city.cityName;
      } else if (user != undefined || user != null) {
        this.cityId = user.cityId;
        this.cityName = user.cityName;
        var city = {
          id:user.cityId,
          cityName:user.cityName
        }
        LocalStorageUtils.setItem("city",city);
      } else {
        this.cityId = 1;
        this.cityName = "福州市";
        var city = {
          id:1,
          cityName:"福州市"
        }
        LocalStorageUtils.setItem("city",city);
      }

      this.getCity();
      this.init(-1);
      //初始化购物车信息
      this.initCart();
      this.getActiveDay();
      var openId = this.$route.query.openid;
      var QRCodeId = this.$route.query.QRCodeId;
      if (!openId){
          openId = "iamopenid"
      }
      //QRCodeId = "850611";
      if (QRCodeId){
          this.set_QRCodeId(QRCodeId);
      }
      LocalStorageUtils.setItem("openid",openId);
      this.set_openid(openId);
    },

  }

</script>
<style lang="less">
 @import './index.less';
</style>
